package org.apache.ibatis.common.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Name EnumOridinalTypeHandler
 * @Description: [SQL Int Oridinal -> JAVA Enum] 类型处理器
 * @Version v1.0.0
 * @Author: lichao
 * @Date: 2024-05-10 17:53:31
 **/
public class EnumOridinalTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {
    private final Class<E> type;
    private final E[] enums;

    public EnumOridinalTypeHandler(Class<E> type) {
        if (type == null) throw new IllegalArgumentException("Type 类型参数不能为 null。");
        this.type = type;
        this.enums = type.getEnumConstants();
        if (this.enums == null) {
            String errorMsg = "类型 [" + type.getSimpleName() + "] 不是一个枚举类型。";
            throw new IllegalArgumentException(errorMsg);
        }
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, parameter.ordinal());
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        int oridinal = rs.getInt(columnName);
        if (oridinal == 0 && rs.wasNull()) return null;
        return toOridinalEnum(oridinal);
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        int oridinal = rs.getInt(columnIndex);
        if (oridinal == 0 && rs.wasNull()) return null;
        return toOridinalEnum(oridinal);
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        int oridinal = cs.getInt(columnIndex);
        if (oridinal == 0 && cs.wasNull()) return null;
        return toOridinalEnum(oridinal);
    }

    private E toOridinalEnum(int oridinal) {
        try {
            return enums[oridinal];
        } catch (Exception e) {
            String errorMsg = "无法将 oridinal value [" + oridinal + "] 转换成类型 [" + type.getSimpleName() + "]，错误原因为：" + e;
            throw new IllegalArgumentException(errorMsg, e);
        }
    }
}

